import {
  addBookmark,
  deleteBookmark,
  GetBookmarkList,
} from "@/api/map/bookmark";
import store from "@/store";
import Extent from "@arcgis/core/geometry/Extent";
import Polygon from "@arcgis/core/geometry/Polygon";
import Graphic from "@arcgis/core/Graphic";
import { ElMessage } from "element-plus";
import { map, mapView } from ".";
export const getBookmarkList = (userid: string) => {
  //获取书签列表，并更新入库
  GetBookmarkList(userid).then((res: any) => {
    if (res.status === 200) {
      store.dispatch("bookmark/SET_BOOKMARKLIST", res.data.rows);
    } else {
      ElMessage({ message: res.data.message, type: "warning" });
    }
  });
};

export const addNewBookmark = (bookmarkForm: any) => {
  // 设置截图的质量 format是图片格式jap或者Png quality为图片质量0-100
  var options: any = {
    format: "jpg",
    quality: 30,
  };
  // 添加书签内容
  var imgUrl = mapView
    .takeScreenshot(options)
    .then((screenshot) => {
      return screenshot.dataUrl;
    })
    .then((thumbnailUrl) => {
      //获取书签范围
      let bkExtent = mapView.extent;
      bkExtent.type = "extent";

      console.log("当前地图", map);
      // map.layers[map.layers.length-1]
      // 获取当前绘制的图形等
      var graphics = mapView.graphics;
      let inputData = {
        mainData: {
          TenantaID: bookmarkForm.userid,
          name: bookmarkForm.name,
          thumbnail: thumbnailUrl,
          geometry: JSON.stringify(graphics),
          bookmarkExtent: JSON.stringify(bkExtent),
          currShowLayerId: "",
          remark: "",
        },
        detailData: null,
        delKeys: null,
      };
      //添加书签
      addBookmark(inputData).then((res: any) => {
        console.log("添加书签成功", res);
        if (res.data.status) {
          // ElMessage({ message: res.data.message, type: "success" });
          getBookmarkList(bookmarkForm.userid);
        } else ElMessage({ message: res.data.message, type: "error" });
      });
    });
};

export const deleteBookmarkById = (id: string, userId: string) => {
  deleteBookmark(id).then((res) => {
    console.log("删除书签", res);
    if (res.status === 200 && res.data.status) {
      // ElMessage({ message: res.data.message, type: "success" });
      getBookmarkList(userId);
    } else {
      ElMessage({ message: res.data.message, type: "error" });
    }
  });
};

/**
 * 书签定位
 * @param {需要定位的书签}} bookmark
 */
export function bookmarkLocate(bookmark: any) {
  let _bookmarkExtent = JSON.parse(bookmark.bookmarkExtent);
  let extentObj = new Extent(_bookmarkExtent);
  mapView.goTo(
    {
      target: extentObj,
    },
    {
      duration: 2000,
    }
  );
}
